import 'package:get/get.dart';
import 'package:oramemo/common/utils/dialog_util.dart';
import 'package:oramemo/core/models/api_response.dart';
import 'package:oramemo/core/repositories/default_api.dart';
import 'package:oramemo/entity/base_entity.dart';
import 'package:oramemo/entity/user_white_entity.dart';
import '../models/user.dart';
import 'package:oramemo/common/langs/text_key.dart';

class UserManagementLogic extends GetxController {
  final RxList<User> users = <User>[].obs;
  final RxList<User> filteredUsers = <User>[].obs;

  @override
  void onInit() {
    loadUsers();
    super.onInit();
  }

  // 加载用户列表
  Future<void> loadUsers() async {
    try {
      final res = await DefaultApi().oraUserWhiteQueryGet<UserWhiteEntity>();
      List<User> list = [];
      for (final UserWhiteRows row in res?.rows ?? []) {
        list.add(User(
            id: row.id.toString(),
            userId: row.userId.toString(),
            name: row.whiteName ?? '',
            phone: row.whitePhone ?? '',
            role: TextKey.userEditDialogDefaultRole.tr,
            avatarUrl: ''));
      }
      users.value = list;
      filteredUsers.value = users;
    } catch (e) {
      TipUtil.showError(TextKey.userManagementLoadError.tr);
    }
  }

  // 搜索用户
  void searchUsers(String query) {
    if (query.isEmpty) {
      filteredUsers.value = users;
      return;
    }

    query = query.toLowerCase();
    filteredUsers.value = users.where((user) {
      return user.name.toLowerCase().contains(query) ||
          user.id.toLowerCase().contains(query);
    }).toList();
  }

  // 添加白名单
  Future<void> addUser(User user) async {
    try {
      final res = await DefaultApi().oraUserWhiteAddPost<BaseEntity>(
          whiteName: user.name, whitePhone: user.phone, isShowLoading: true);
      if (res?.isSuccess == true) {
        loadUsers();
        TipUtil.showSuccess(TextKey.whitelistAddSuccess.tr);
      } else {
        TipUtil.showError(res?.msg ?? TextKey.whitelistAddError.tr);
      }
    } catch (e) {
      TipUtil.showError(TextKey.whitelistAddError.tr);
    }
  }

  // 编辑白名单
  Future<void> editUser(User user) async {
    try {
      final res = await DefaultApi().oraUserWhiteEditPost<BaseEntity>(
          id: user.id, whiteName: user.name, whitePhone: user.phone);
      if (res?.isSuccess == true) {
        final index = users.indexWhere((element) => element.id == user.id);
        if (index != -1) {
          users[index] = user;
          final filteredIndex =
              filteredUsers.indexWhere((element) => element.id == user.id);
          if (filteredIndex != -1) {
            filteredUsers[filteredIndex] = user;
          }
          TipUtil.showSuccess(TextKey.whitelistEditSuccess.tr);
        }
      }
    } catch (e) {
      TipUtil.showError(TextKey.whitelistEditError.tr);
    }
  }

  // 删除白名单
  Future<void> deleteUser(String userId) async {
    try {
      final res = await DefaultApi()
          .oraUserWhiteIdsDelete<BaseEntity>(ids: userId, isShowLoading: true);
      if (res?.isSuccess == true) {
        users.removeWhere((user) => user.id == userId);
        filteredUsers.removeWhere((user) => user.id == userId);
        TipUtil.showSuccess(TextKey.whitelistDeleteSuccess.tr);
      }
    } catch (e) {
      TipUtil.showError(TextKey.whitelistDeleteError.tr);
    }
  }
}
